<template>
  <div class="my-tag">
    <input
      v-if="isEdit"
      @blur="change"
      @keyup.enter="change"
      v-model="msg"
      ref="inp"
      class="input"
      type="text"
      placeholder="输入标签"
    />
    <div v-else @dblclick="fn" class="text">{{ name }}</div>
  </div>
</template>

<script>
export default {
  props: {
    name: {
      required: true,
      type: String
    }
  },
  // 修改外界使用v-model产生的语法糖
  // 此时会产生 :name="数据" @xx="数据=$event"
  model: {
    prop: 'name',
    event: 'xx'
  },
  data () {
    return {
      isEdit: false,
      msg: ''
    }
  },
  methods: {
    change () {
      // 拿到输入的内容
      this.$emit('xx', this.msg)
      // 结束编辑状态-也就是隐藏输入框
      this.isEdit = false
    },
    async fn () {
      // 1. 显示出输入框
      this.isEdit = true
      // 2. 把文字渲染到输入框里
      this.msg = this.name

      // 用$nextTick -- 因为dom渲染是异步的，我们一定等本次dom渲染完才让让输入框获得焦点
      await this.$nextTick()
      // 3. 让输入框获得焦点
      this.$refs.inp.focus()
    }
  }
}
</script>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
</style>
